// pages/pk-loading.js
var app = getApp();
const setting = require("../../http/env");
const httpApi = require("../../http/request"); //后续可以改为你自己的域名接口地址
let socket = null; //全局定义socket对象
let socketOpen = false; //是否开启websoket
let timer = null;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //默认域名
    baseUrl: setting.baseUrl,
    //答题匹配id
    quest_rule_id: 0,

    //房主
    initiate_user: "",
    //匹配人
    match_user: "",

    //匹配成功
    mate_success: false,
    musicVideo: null,
    showBaseUrl: false
  },

  //数据回调
  mycallback(data) {
    var start = data.indexOf("["); // 第一次出现的位置
    var start1 = data.indexOf("{");

    if (start < 0) {
      start = start1;
    }
    if (start >= 0 && start1 >= 0) {
      start = Math.min(start, start1);
    }

    if (start >= 0) {
      // console.log(data);
      var json = data.substr(start); //截取
      var json = JSON.parse(json);
      return json;
    } else {
      return "";
    }
  },

  //进行匹配
  send() {
    var that = this;
    if (socketOpen) {
      var param = {
        type: "freedom",
        data: [
          {
            user_id: that.data.user.id,
            quest_rule_id: that.data.quest_rule_id,
          },
        ],
      };
      socket.send({
        data: JSON.stringify(param),
        success: function (e) {
          console.log(e);
        },
      });
    }
  },

  //接收信息
  geMessage(data) {
    var that = this;
    //房主创建房间展示
    if (data && data[0] == "quest_rule_id") {
      var initiate_user = that.data.user;
      if (initiate_user.sorce > 999) {
        initiate_user.sorce = "999+";
      }

      that.setData({
        quest_rule_id: data[1],
        initiate_user: initiate_user,
        showBaseUrl: !initiate_user.headimg.includes('http')
      });
      //开始倒计时
      that.setRobotTime();
    }
    //匹配人进入房间
    if (data && data[0] == "data") {
      this.playVideo();
      var initiate_user = data[1].initiate_user;
      var match_user = data[1].match_user;

      if (initiate_user.sorce > 999) {
        initiate_user.sorce = "999+";
      }
      if (match_user.sorce > 999) {
        match_user.sorce = "999+";
      }

      that.setData({
        initiate_user: initiate_user,
        match_user: match_user,
      });

      //开始比赛操作
      that.startGame();
    }
    //开始比赛
    if (data && data[0] == "quest_game_id") {
      that.setData({
        mate_success: true,
      });

      setTimeout(() => {
        wx.redirectTo({
          url: "../start-fighting/start-fighting?quest_game_id=" + data[1] + '&initiate_user_id=' + this.data.initiate_user.id + '&match_user_id=' + this.data.match_user.id,
        });
      }, 1000);
    }
  },

  //开始比赛
  startGame(e) {
    var that = this;
    if (socketOpen) {
      var param = {
        type: "game",
        data: [
          {
            quest_rule_id: that.data.quest_rule_id,
          },
        ],
      };
      socket.send({
        data: JSON.stringify(param),
        success: function (e) {
          console.log(e);
        },
      });
    }
  },

  // 匹配机器人倒计时器
  setRobotTime() {
    var that = this;
    let timeCount = 2;
    timer = setInterval(() => {
      timeCount--;
      console.log(timeCount);
      if (timeCount <= 0) {
        clearInterval(timer);
        if (!that.data.mate_success) {
          that.send();
        }
      }
    }, 1000);
  },

  //是否关闭了门店
  shopClose(e){
    var that=this;
    var user = that.data.user;
    var params={
      unitid:user.unitid,
    };
    httpApi.Post("/index/shopClose", params).then((res) => {
      // console.log("data", res);

      if(res.is_close==1 || res.is_end==1){
        wx.redirectTo({
          url: '../home/home',
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    //用户数据
    var user = wx.getStorageSync("userInfo");

    //参数判断
    if (!user) {
      wx.redirectTo({
        url: "../home/home",
      });
    }

    //保存数据
    that.setData({
      user: user,
    });

    if(user){
      //判断是否关闭
      that.shopClose();

      // 建立 WebSocket 连接
      socket = wx.connectSocket({
        url: setting.ws,
        header: {
          "content-type": "application/json",
        },
        success(res) {
          console.log("WebSocket 连接成功: ", res);
        },
        fail(err) {
          console.log("WebSocket 连接失败: ", err);
        },
      });
      // onOpen
      socket.onOpen(() => {
        console.log("打开 WebSocket 连接");
        socketOpen = true;
        //发送请求
        that.send();
        console.log(new Date());
      });
      // onError
      socket.onError((err) => {
        console.log("WebSocket 连接失败：", err);
        socketOpen = false;
      });
      // onClose
      socket.onClose((ret) => {
        console.log("断开 WebSocket 连接", ret);
        socketOpen = false;
        console.log(new Date());
      });
      //监听接收到的消息
      socket.onMessage((res) => {
        let msg = res.data;
        var getData = that.mycallback(msg);
        console.log("接收到的服务器消息", getData);
        that.geMessage(getData);
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  // 播放音频
  playVideo() {
    this.data.musicVideo = wx.createInnerAudioContext({
      useWebAudioImplement: true,
    });
    this.data.musicVideo.loop = true; // 循环
    this.data.musicVideo.src =
      "https://game.shuguos.com/upload/video/pk-loading.mp3";
    this.data.musicVideo.play(); // 播放
  },
  // 停止播放音频并释放
  stopVideo() {
    if (this.data.musicVideo) {
      this.data.musicVideo.stop(); // 停止音频资源
      this.data.musicVideo.destroy(); // 释放音频资源
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.stopVideo();
    clearInterval(timer);
    socket.close();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    var user=wx.getStorageSync("userInfo");
    var path='/pages/home/home?unitid='+user.unitid+'&unitid_copy='+user.unitid_copy + "&inviterId=" + wx.getStorageSync("userInfo").id;
    return {
      title: app.globalData.shareInfo[e.from].title,
      imageUrl: app.globalData.shareInfo[e.from].imageUrl,
      path: path,
      success: function(res) {
        // 转发成功
        console.log(11212);
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
});
